//
// Created by guanzhe on 15/12/28.
// Copyright (c) 2015 MengHuan. All rights reserved.
// 号池管理

#import "NumPoolManageVc.h"
#import "Usermodel.h"
#import "BaseTableView.h"
#import "CommonSearchBar.h"
#import "UIViewController+common.h"
#import "UIColor+Extension.h"
#import "BaseTableCell.h"
#import "NumPoolCell.h"
#import "cardChooseView.h"
#import "DataModel.h"
#import "NumPoolEditVc.h"

static const NSString *cellIdentifier = @"NumPoolCell";

@interface NumPoolManageVc()<UITableViewDelegate, UITableViewDataSource,CommonClickDelegate,UITextFieldDelegate,cardChooseViewDelegate,UIAlertViewDelegate>{
    NSMutableArray *_tableDataArr;
    NSMutableArray *_poolManageArr;
    NSString *_num;//搜索用的渠道号 一开始为空
    cardChooseView *_cardChooseView;
    UIAlertView *_deleteAlertView;
    MsgModel *_deleteModel;
    CommonModel *_commonModel;
}

@property (weak, nonatomic) IBOutlet UITextField *searchTf;
@property(weak, nonatomic) IBOutlet BaseTableView *tableView;
@property(nonatomic, assign) int page;//某些请求数据有页码的页面用到的参数
@end
@implementation NumPoolManageVc {

}

- (void)viewDidLoad {
    [super viewDidLoad];
    NAV_INIT(self, @"号池列表", @"back", @selector(backButtonClick:), @"添加", @selector(rightBtnClick));
    [self initTab];
    self.searchTf.placeholder = @"--请选择--";
    self.searchTf.delegate = self;
    _deleteAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确认要删除此号池吗" delegate:self
                                        cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil ];
    [_deleteAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_deleteAlertView dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.header beginRefreshing];
}

- (void)initChooseView{
    _cardChooseView = [[[NSBundle mainBundle] loadNibNamed:@"cardChooseView" owner:nil options:nil] lastObject];
    _cardChooseView.delegate = self;
    NSMutableArray *cardList = [NSMutableArray array];
    [cardList addObject:[SelectTypeBean beanWithId:@"" name:@"全部"]];
    for(DitchManageModel *ditchManageModel in _poolManageArr){
        [cardList addObject:[SelectTypeBean beanWithId:ditchManageModel.servicerCode name:[ditchManageModel.userName stringByAppendingString:[[@"(" stringByAppendingString:[NSString ignoreEmptyStr:ditchManageModel.servicerCode]] stringByAppendingString:@")"]]]];
    }
    _cardChooseView.cardList = cardList;
    self.searchTf.inputView = _cardChooseView;
}

- (void)cancel {
    [self.view endEditing:YES];
}

- (void)chooseCard:(SelectTypeBean *)cardInfo {
    [self.view endEditing:YES];
    self.searchTf.text = cardInfo.name;
    self.page = 1;
    _num = cardInfo.id;//放置渠道id
    [self requestList];
}

- (void)cardChooseView:(UIPickerView *)cardChooseView didSelectRow:(NSInteger)row withCardBean:(SelectTypeBean *)cardInfo {

}

- (void)rightBtnClick {
    if(_commonModel == nil){
        return;
    }
    if(_commonModel.addFlag.description.intValue != 1){
        [SVProgressHUD showErrorWithStatus:@"您无权限执行此操作"];
        return;
    }
    NumPoolEditVc * numPoolEditVc = kHome_storyVCName(@"NumPoolEditVc");
    numPoolEditVc.type = POOL_NEW_TYPE;
    [self.navigationController pushViewController:numPoolEditVc animated:YES];
}

- (void)initTab {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor backgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableFooterView.backgroundColor = [UIColor backgroundColor];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page = 1;
        [self requestList];
    }];
    [self.tableView addFooterRefreshTarget:self action:@selector(requestLoadMoreDataByPage)];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (toBeString.length > 0 && range.length!=1){ //最大0个字符
        textField.text = [toBeString substringToIndex:0];
        return NO;
    }
    if ([string chenkInputNSCharacterSetWithType:6])//kEmpty
    {
        return YES;
    }
    else
        return NO;
}

//alert delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [UserServices deletePoolByToken:[[AppDelegate appDelegate] getUserInfo].token
                                 poolId:_deleteModel.id
                       completionBlock:^(int result, id responseObject) {
                           [_tableDataArr removeObject:_deleteModel];
                           [self.tableView reloadData];
                       }];
    }
}

#pragma click

- (void)clickActionWithData:(JSONModel *)data AndType:(NSString *)type {
    MsgModel *msgModel = (MsgModel *)data;
    if([@"repair" isEqualToString:type]){
        if(_commonModel.modFlag.description.intValue != 1){
            [SVProgressHUD showErrorWithStatus:@"您无权限执行此操作"];
            return;
        }
        NumPoolEditVc * numPoolEditVc = kHome_storyVCName(@"NumPoolEditVc");
        numPoolEditVc.type = POOL_EDIT_TYPE;
        numPoolEditVc.model = msgModel;
        [self.navigationController pushViewController:numPoolEditVc animated:YES];
    }else{
        if(_commonModel.delFlag.description.intValue != 1){
            [SVProgressHUD showErrorWithStatus:@"您无权限执行此操作"];
            return;
        }
        _deleteModel = msgModel;
        [_deleteAlertView show];
    }

}


#pragma mark 返回分组数

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


#pragma mark head的高度

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

#pragma mark 返回每组行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _tableDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

#pragma mark返回每行的单元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NumPoolCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
        cell = [[[UINib nibWithNibName:cellIdentifier bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    [cell setCellInfo:_tableDataArr andPosition:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark 底部刷新

- (void)requestLoadMoreDataByPage {
    self.page++;
    [self requestList];
}

//获取号池
- (void)requestList {
    [UserServices getNumPoolListByToken:[[AppDelegate appDelegate] getUserInfo].token
                               servicer:_num
                                   page:kIntToString(_page)
                               pagesize:kIntToString(kListPageSize)
                        completionBlock:^(int result, id responseObject) {
                            if (result == API_Request_Success) {
                                _commonModel = (CommonModel *)responseObject;
                                _poolManageArr = (NSArray *)_commonModel.serList;
                                [self initChooseView];
                                NSMutableArray *array = (NSArray *)_commonModel.poolPage;
                                if (self.page == API_Request_Success) {
                                    _tableDataArr = array;
                                    [self.tableView.footer resetNoMoreData];//重置有更多数据
                                    if (array == nil || array.count == 0) {
                                        //提示无数据
                                        [SVProgressHUD showErrorWithStatus:@"查无数据"];
                                    } else {
                                    }
                                }
                                else
                                    [_tableDataArr addObjectsFromArray:array];
                                if (array.count == 0) {
                                    self.page--;
                                }
                                [self.tableView.header endRefreshing];
                                [self.tableView.footer endRefreshing];
                                [self.tableView reloadData];
                                if (array.count < kListPageSize)
                                    [self.tableView.footer noticeNoMoreData];//没有更多数据
                            } else {//出错时的处理
                                //提示出错
                                [SVProgressHUD showErrorWithStatus:Error_Format];
                            }
                        }];
}




@end

